package com.gitee.magic.converter;

import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import com.gitee.magic.core.converter.AbstractConverterEditor;

/**
 * @author start
 */
public class DateConverterEditor extends AbstractConverterEditor<Date> {

	public DateConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if(value!=null) {
			setValue(restoreDataValue(value));
		}
	}

	@Override
	public Date converter() {
		if(getValue()!=null) {
			return (Date)getValue();
		}
		return null;
	}
	
	public static Object restoreDataValue(Object value) {
		if(value.getClass().equals(Timestamp.class)) {
			return new Date(((Timestamp)value).getTime());
		}else if(value.getClass().equals(java.sql.Date.class)) {
			return new Date(((java.sql.Date)value).getTime());
		}else if(value.getClass().equals(Time.class)) {
			return new Date(((Time)value).getTime());
		}else if(value.getClass().equals(LocalDateTime.class)) {
			LocalDateTime localDateTime = (LocalDateTime)value;
			return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
		}else {
			return value;
		}
	}

}
